package net.flowas.genericcrud.service.chain;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;

import net.flowas.genericcrud.ExecuteContext;
import net.flowas.genericcrud.RepositoryService;
import net.flowas.genericcrud.dto.PageModdel;

public class CrudExecuteHandler  extends AbstractExecuteHandler{
	private RepositoryService repositoryService;
	public CrudExecuteHandler(ExecuteHandler next,RepositoryService repositoryService) {
		super(next);
		this.repositoryService=repositoryService;
    }
	@Override
	  public void handleRequest(ExecuteContext req) {
		  switch (req.getAction()) {
		case COUNT:
			Long result = repositoryService.count(req.getQueryOption(), req.getModelClass());
			req.setResult(result);
			break;
		case QUERY:
	    	List list = repositoryService.findRang(req.getQueryOption(), req.getModelClass());
	    	req.setResult(list);
	    	break;
	    case QUERY_COUNT:
	    	PageModdel page = repositoryService.queryWithCount(req.getQueryOption(), req.getModelClass());
	    	req.setResult(page);
	    	break;
	    case CREATE:
	    case MERGE:
	    case UPDATE:
	    	 Object merged = repositoryService.saveOrUpdate(req.getQueryOption().getExample());
	    	 req.setResult(merged);
	    	 break;	    
	    case GET:
	    	Object item =repositoryService.findById(req.getModelClass(), req.getQueryOption().getExample());
	    	req.setResult(item);
	    	break;
	    case DELETE:
	    	repositoryService.remove(req.getModelClass(), req.getQueryOption().getExample());
	    	break;
	    default:
			break;
		}
		  super.handleRequest(req);
	  }
	  @Override
	  public Collection<Class<? extends Serializable>> getHandledTypes() {
	    return repositoryService.getHandledTypes();
	  }
}
